#ifndef __MY_HOT__
#define __MY_HOT__
#include <string>
#include <unistd.h>
#include "Config.hpp"
#include "Util.hpp"
#include "DataManage.hpp"

extern cloud::DataManager *data;
namespace cloud
{
    class HotManager
    {
    private:
        int _hot_time;
        std::string _back_dir;
        std::string _pack_dir;
        std::string _pack_suffix;

    public:
        HotManager()
        {
            Config *config = Config::GetInstance();
            _hot_time = config->GetHotTime();
            _back_dir = config->GetBackDir();
            _pack_dir = config->GetPackDir();
            _pack_suffix = config->GetPackfileSuffix();
            FileUtil tmp1(_back_dir);
            FileUtil tmp2(_pack_dir);
            tmp1.CreateDirectory();
            tmp2.CreateDirectory();
        }
        bool HotJudge(std::string filename)
        {
            FileUtil fu(filename);
            time_t last_atime = fu.LastATime();
            time_t cur_time = time(nullptr);
            if (cur_time - last_atime > _hot_time)
            {
                return true;
            }
            return false;
        }
        void RunModule()
        {
            while (true)
            {
                // 1.遍历整个备份目录，获取所有文件名
                FileUtil fu(_back_dir);
                std::vector<std::string> array;
                fu.ScanDirectory(&array);

                // 2.根据文件名获取最近一次访问时间，然后判断是否是非热点文件
                for (auto &a : array)
                {
                    // 3.如果是非热点文件，就把文件压缩然后存放到压缩后的目录，然后删除掉源文件
                    if (HotJudge(a) == false)
                    {
                        continue;
                    }
                    FileUtil tmp(a);
                    std::string filename = tmp.FileName();

                    //获取pack_path
                    BackupInfo info;
                    if(data->GetOneByRealPath(a, &info) == false)
                    {
                        info.NewBackupInfo(a, &info);
                        data->Insert(info);
                    }

                    std::string packname = info.pack_path;
                    tmp.Compress(packname);

                    //4.删除源文件
                    tmp.Remove();

                    // 5.修改文件数据信息
                    info.pack_flag = true;
                    data->Update(info);
                }
                usleep(1000);
            }
        }
    };
}

#endif